<?php


namespace app\admin\controller;


use app\admin\model\FromConfig;
use app\common\controller\admin\Base;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Fromcnfig extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\FromConfig();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $categoryId = $this->request->post('category_id', '');
            $sort = $this->request->post('sort', 'weight');
            $order = $this->request->post('order', 'desc');
            $adminId = $this->request->post('admin_id', '');
            $countryConfigId = $this->request->post('country_config_id', '');
            if (empty($categoryId)) {
                $this->error('category_id缺失！');
            }
            if (empty($countryConfigId)) {
                $this->error('country_config_id缺失！');
            }
            if ($adminId != '') {
                $where['admin_id'] = $adminId;
            }
            $where['category_id'] = $categoryId;
            $where['country_config_id'] = $countryConfigId;
            $where['is_del'] = 0;
            $list = $this->model
                ->field('*')
                ->where($where)
                ->order($sort, $order)
                ->select();
            $data = [
                'list' => $list
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 获取表单配置
     */
    public function getFormConfigInfo($country_config_id)
    {
        $where = [
            'is_del' => 0,
            'status' => 1
        ];
        $catList = \app\admin\model\Category::field('id,nickname')->where($where)->where('pid', '=', 33)->select()->toArray();
        $where['country_config_id'] = $country_config_id;
        $fromList = FromConfig::field('name,title,type,value,category_id')->where($where)->order('weight', 'desc')->select()->toArray();
        $list = [];
        foreach ($catList as $val) {
            $info = [];//初始化数组
            $info = $val;
            $info['from_list'] = [];
            foreach ($fromList as $v) {
                if ($v['category_id'] == $val['id']) {
                    unset($v['category_id']);
                    $info['from_list'][] = $v;
                }
            }
            $list[] = $info;
        }
        return $list;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $ids = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $params['create_time'] = time();
                    $ids = $this->model->allowField(true)->insertGetId($params);
                    $this->model->where('id', $ids)->update(['weight' => $ids]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($ids !== false) {
                    $this->success('添加成功', '', ['ids' => $ids]);
                } else {
                    $this->error('添加失败');
                }

            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 权重调换
     * @param $ids
     * @param $exchange_ids
     */
    public function weightExchange($ids, $exchange_ids)
    {
        $row = $this->model->get($ids);
        $exchangeRow = $this->model->get($exchange_ids);
        if (!$row || !$exchangeRow) {
            $this->error('不存在的数据', '', [], 404);
        }
        try {
            $exchangeWeight = $exchangeRow['weight'];
            $rowWeight = $row['weight'];
            $row->allowField(true)->isUpdate(true)->save(['weight' => $exchangeWeight]);
            $exchangeRow->allowField(true)->isUpdate(true)->save(['weight' => $rowWeight]);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改成功');

    }
}